<template>
  <div>
    <el-dialog
      title="新增"
      :visible="visible"
      width="80%"
      @close="visible = false"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-form"
        label-position="top"
        size="mini"
        style="width: 100%"
        v-loading="loading"
      >
        <el-form-item
          label="表单名称"
          prop="workflowId"
          :label-width="defaultLabelWidth"
        >
          <el-select
            filterable
            style="width: 100%"
            v-model="form.workflowId"
            placeholder="请选择"
            default-first-option
          >
            <el-option
              v-for="item in allWorkflows"
              :key="item.id + item.activeVersion"
              :label="item.name"
              :value="item.id + ':' + item.activeVersion"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="标题"
          prop="title"
          :label-width="defaultLabelWidth"
        >
          <el-input
            disabled
            size="mini"
            type="text"
            v-model="form.title"
          ></el-input>
        </el-form-item>

        <el-form-item label="表单数据" prop=""> </el-form-item>

       
      </el-form>
      <el-card shadow="never">
        <controlPanel ref="controlPanel" :isEdit="true"></controlPanel>
      </el-card>
       <!-- 审批进度 -->
       <forecastNodeUser ref="forecastNodeUser"></forecastNodeUser>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirm" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import controlPanel from "./../formDesign/controlPanel.vue";
import forecastNodeUser from "./../formInstance/components/forecastNodeUser.vue";
import defaultToVfrom from "@/views/workflows/formDesign/designContentConverters/defaultToVfrom";
export default {
  components: { controlPanel, forecastNodeUser },
  props: {
    value: {
      id: 1,
    },
  },
  watch: {
    value: {
      handler() {
        //this.load();
      },
      deep: true,
    },
    visible(newVal, oldVal) {
      if (!newVal && oldVal) this.hide();
    },
    "form.workflowId": {
      handler() {
        if (!this.form.workflowId) {
          return;
        }

        console.log(this.$store.state);

        const date = new Date();
        const workflows = this.allWorkflows.filter(
          (item) => item.id + ":" + item.activeVersion === this.form.workflowId
        );
        this.form.title = `${this.$store.state.user.user.name}-${
          workflows[0].name
        }审批-${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;

        var workflowId = this.form.workflowId.split(":");
        this.workTaskForm.workflowId = {
          id: workflowId[0],
          versionNo: workflowId[1],
        };
        this.changeFormDesign({ id: workflowId[0], version: workflowId[1] });
      },
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  data() {
    return {
      loading: false,
      visible: false,
      defaultLabelWidth: "150px",
      form: {
        title: "",
      },
      rules: {
        title: [{ required: true, message: "请输入", trigger: "change" }],
        workflowId: [{ required: true, message: "请选择", trigger: "change" }],
      },
      allWorkflows: [],
      formDesign: {},
      workTaskForm: {
        entityFullName: "dynamicForm",
        entityKeyValue: "",
        formData: "{}",
        workTaskStatus: "",
        name: "",
        workflowId: {},
      },
    };
  },
  methods: {
    confirm() {
      this.commit();
    },
    show(value) {
      this.visible = true;
      this.getAllWorkflowsWithVersion();
      this.watchForecastNodeUsers();
      if (value) this.loadData(value);
    },
    hide() {
      this.visible = false;
      this.form = {
        name: "",
      };
    },
    loadData(value) {
      this.loading = true;
      Object.keys(value).forEach((key) => {
        this.form[key] = value[key];
      });
      this.loading = false;
    },
    commit() {
      const _this = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.createWorkTask();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    changeFormDesign(value) {
      this.loading = true;
      this.getDesign(value).then((controls) => {
        this.loading = false;
        //this.$set(this.form, "formData", JSON.parse(res.formData || "{}"));
        this.$refs.controlPanel.setValue(controls, {});
      });
    },
    getDesign(id) {
      return this.$store
        .dispatch("dynamicFormDesign/getFormDesignVersionByWorkflowId", id)
        .then((res) => {
          this.formDesign = res;
          if (res && res.designContent) {
            if (res.designFramework != "vform") {
              return defaultToVfrom(res.designContent);
            } else {
              return JSON.parse(res.designContent || "{}");
            }
          } else return null;
        });
    },

    createWorkTask() {
      this.loading = true;

      //做关联数据处理
      let formDesign = this.formDesign || {};
      //这里干脆将数据用json字符串保存，便于反序列（编辑查看）
      this.workTaskForm.entityKeyValue = JSON.stringify({
        id: formDesign.formDesignId,
        versionNo: formDesign.version,
        time: new Date().getTime(),
      }); //这里记录表单设计的id和版本，用户查看时，回显数据
      this.workTaskForm.name = this.form.title;
      this.workTaskForm.formData = JSON.stringify(
        this.$refs.controlPanel.getValue()
      );

      const formData = { ...this.workTaskForm };
      formData.workflowId = this.workTaskForm.workflowId.id;

      let _this = this;
      let dispatchPath = "workflow/createWorkTaskWithDefaultVersion";
      this.$store
        .dispatch(dispatchPath, formData)
        .then((res) => {
          this.loading = false;
          this.hide();
          this.$emit("ok-click");
          return res;
        })
        .catch((e) => {
          this.loading = false;
        });
    },
    getAllWorkflowsWithVersion() {
      this.loading = true;
      this.$store
        .dispatch("workflow/getAllWorkflowsWithDefaultVersion", this.form)
        .then((res) => {
          this.allWorkflows = res;
          this.loading = false;
        });
    },
    watchForecastNodeUsers() {
      setTimeout(() => {
        if (!this.$refs.controlPanel) {
          this.watchForecastNodeUsers();
          return;
        }
        let formData = JSON.stringify(this.$refs.controlPanel.getValue());
        if (this.$refs.forecastNodeUser) {
          this.$refs.forecastNodeUser.getForecastNodeUsers4Workflow({
            formData: formData,
            workflowId: this.workTaskForm.workflowId.id,
            versionNo: this.workTaskForm.workflowId.versionNo,
          });
        }
        this.watchForecastNodeUsers();
      }, 600);
    },
  },
};
</script>

<style></style>
